<template>
  <div>
    <div class="Wokoo" v-if="config_menu_show" v-loading.fullscreen.lock="fullscreenLoading" disabled="disabled">
      <header class="Wokoo-header">
      <span
          class="Wokoo-close-icon"
          @click="handleClose"
      >
        ×
      </span>
        <div class="title">
          纷享销客助手 v1.3.5<span>@是小勋勋啊</span>
        </div>
      </header>
      <div class="menu">
        <!--        <el-divider content-position="left">陈列检核</el-divider>-->
        <!--        <el-row>-->
        <!--          <el-col :span="24">-->
        <!--            <el-switch-->
        <!--                :value="config_checked_chenlie"-->
        <!--                @change="handleClickChecked_chenlie('')"-->
        <!--                active-text="自动更新陈列形式"-->
        <!--            />-->
        <!--            <el-popover-->
        <!--                placement="top"-->
        <!--                title="功能提示"-->
        <!--                width="240"-->
        <!--                trigger="hover"-->
        <!--                content="将活动协议列自动修改成陈列形式">-->
        <!--              <i style="color: cornflowerblue;font-weight: 800" class="el-icon-warning-outline" slot="reference"></i>-->
        <!--            </el-popover>-->
        <!--          </el-col>-->
        <!--          <el-col :span="24" style="margin-top: 10px;margin-left: 20px">-->
        <!--            <el-switch-->
        <!--                :value="config_checked_chenlie_ceng"-->
        <!--                active-text="显示层数规则"-->
        <!--                :disabled="!config_checked_chenlie"-->
        <!--                @change="handleClickChecked_chenlie('ceng')"-->
        <!--            />-->
        <!--          </el-col>-->
        <!--          <el-col :span="24" style="margin-top: 10px;margin-left: 20px">-->
        <!--            <el-switch-->
        <!--                :value="config_checked_chenlie_paimian"-->
        <!--                active-text="显示排面规则"-->
        <!--                :disabled="!config_checked_chenlie"-->
        <!--                @change="handleClickChecked_chenlie('paimian')"-->
        <!--            />-->
        <!--          </el-col>-->
        <!--        </el-row>-->
        <div style="margin-top: 40px">
          <el-row class="row-bg" justify="space-around">
            <el-col :span="12">
              <div @click="showTourAdminDrawer=true">
                <tool-item-card title="巡店管理后台" desc="自研v3.0版本" :src="toolXundian"/>
              </div>
            </el-col>
            <el-col :span="12">
              <div @click="showClientAdminDrawer=true">
                <tool-item-card title="网点归属查询" desc="查看网点明细" :src="toolClient"/>
              </div>
            </el-col>
            <el-col :span="12">
              <div @click="showFeeManagerDrawer=true">
                <tool-item-card title="费用小组" desc="费用专员工具箱" :src="toolWallet"/>
              </div>
            </el-col>
            <el-col :span="12">
              <div @click="dialogVisible_shenpi=true">
                <tool-item-card title="批量审批" desc="费用专员陈列审批" :src="toolShenpi"/>
              </div>
            </el-col>
            <el-col :span="12">
              <div @click="showTestDrawer=true">
                <tool-item-card :src="toolMore"/>
              </div>
            </el-col>
          </el-row>
          <el-drawer
              :visible.sync="showTourAdminDrawer"
              :with-header="false"
              :modal="false"
              size="80%"
          >
            <tour-admin/>
          </el-drawer>
          <el-drawer
              :visible.sync="showClientAdminDrawer"
              :with-header="false"
              :modal="false"
              size="80%"
          >
            <client-admin/>
          </el-drawer>
          <el-drawer
              :visible.sync="showFeeManagerDrawer"
              :with-header="false"
              :modal="false"
              size="90%"
          >
            <el-row>
              <el-col :span="18">
                <fee-manager ref="fee-manager" @refreshShopList="refreshShopList"/>
              </el-col>
              <el-col :span="6">
                <verify-shop-list-view ref="verify-shop-list-view"/>
              </el-col>
            </el-row>
          </el-drawer>
          <el-drawer
              :visible.sync="showTestDrawer"
              :with-header="false"
              :modal="false"
              size="80%"
          >
            <test-function-view/>
          </el-drawer>
        </div>
        <div style="margin-top: 6vh">
          <el-divider content-position="left">杂项功能</el-divider>
          <el-row>
            <el-col :span="24">
              <el-switch
                  :value="config_checked_watermark"
                  @change="handleClickChecked_watermark"
                  active-text="护眼模式（去水印）"
              />
            </el-col>
          </el-row>
        </div>

        <div class="countTo">
          <countTo class="tips" prefix="已累计使用：" suffix="次" :startVal='0' :endVal='countTimes'
                   :duration='3000'></countTo>
        </div>
        <contact-card style="margin-top: 3vh"/>
      </div>
    </div>

    <div class="Wokoo-hide" v-loading.fullscreen.lock="fullscreenLoading" v-draggable v-show="!config_menu_show">
      <img :src="logo" class="Wokoo-hide-logo" alt="logo"/>
      <span @click="handleClose" style="cursor: pointer !important;">打开面板</span>
    </div>
    <el-dialog
        v-if="banned == false"
        class="dialog-content"
        title="👉🏻 工具箱更新提示 👈🏻"
        :visible.sync="updateDialogVisible"
        width="60%"
        :before-close="confirmUpdatesDialog"
        :destroy-on-close="true"
        :show-close="false"
        :close-on-click-modal="false"
        center>
      <p class="tips">
        如果上述更新没有生效，请清除浏览器换存文件并刷新页面，具体方法参考如下链接：
        <a href="https://microsoftedgetips.microsoft.com/zh-cn/search/37?query=%E6%B8%85%E9%99%A4&form=MA13DX"
           target="_blank">Edge浏览器如何清除缓存</a>
        <a href="https://support.google.com/accounts/answer/32050?hl=zh-Hans&co=GENIE.Platform%3DDesktop"
           target="_blank">Chrome浏览器如何清除缓存</a>
        <a href="http://chrome.360.cn/help/cleandata.html" target="_blank">360浏览器如何清除缓存</a>
      </p>
      <span slot="footer" class="dialog-footer">
              <el-button type="warning" @click="confirmUpdatesDialog">朕知道了</el-button>
            </span>
    </el-dialog>
    <el-dialog
        v-else
        class="dialog-content"
        title="👉🏻 亲爱的元气小伙伴们 👈🏻"
        :visible.sync="updateDialogVisible"
        width="40%"
        :before-close="confirmUpdatesDialog"
        :destroy-on-close="true"
        :show-close="true"
        :close-on-click-modal="false"
        center
    >
      <p>5月11日公司发布<a href="https://oa.feishu.cn/announcement/detail/7096347047137312770?lang=zh-CN&open_in_browser=true" target="_blank">《关于元气森林内部禁止使用未授权软件的公告》</a></p>
      <p>【新增】1.费用专员批量提交审批</p>
      <p>【新增】2.费用核查部分功能筛选</p>
<!--      <p>后续如果公司需要，我会将程序开源给技术部门，由公司主导开发</p>-->
<!--      <p>❤️再次感谢测试阶段大家对我的帮助和认可❤️</p>-->
<!--      <p>我们是一群有爱的人在一个有爱的组织传递有爱的产品</p>-->
      <i class="author">
        By：元气铁军
      </i>
      <p class="tips">
        💡小提示：点击右上角的小眼睛，关闭开关即可禁用工具箱
      </p>
    </el-dialog>

    <el-dialog
        title="批量发起陈列审批"
        :visible.sync="dialogVisible_shenpi"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        :show-close="false"
    >
      <span>年份</span>
      <el-input style="margin-top: 10px" v-model="year" type="number" :disabled="true"></el-input>
      <span style="margin-top: 20px; display: block">月份</span>
      <el-input style="margin-top: 10px" v-model="month" type="number" :disabled="true"></el-input>
      <el-progress :percentage="totalShenpiNum==0?100:parseInt((totalShenpiNum-tmp_totalShenpiNum)/totalShenpiNum*100)" style="margin-top: 10px"></el-progress>
      <span slot="footer" class="dialog-footer">
        <el-button type="warning" @click="handleShenpi" :disabled="disable">确 定</el-button>
        <el-button @click="dialogVisible_shenpi = false" :disabled="disable">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import './app.less'
import draggable from './draggable.js'
import logo from '../public/icon.png'
import toolXundian from '../public/tool@xundian.png'
import toolMore from '../public/tool@more.png'
import toolClient from '../public/tool@client.svg'
import toolWallet from '../public/tool@wallet.svg'
import toolShenpi from '../public/tool@shenpi.svg'
import axios from 'axios'
import countTo from 'vue-count-to'
import ContactCard from "./components/ContactCard.vue";
import TourAdmin from "./components/TourAdmin.vue";
import ClientAdmin from "./components/ClientAdmin.vue";
import FeeManager from "./components/FeeManager.vue";
import ToolItemCard from "./components/ToolItemCard.vue";
import TestFunctionView from "./components/TestFunctionView.vue";
import VerifyShopListView from "./components/VerifyShopListView.vue";

import {
  api_getFkChenlieType,
  api_getDaishenpi,
  api_getZeroSalesNumber,
  api_getCheckInSearchResult,
  api_getAPIKeyDict,
  api_getShenpiList,
  api_chenlieShenpi
} from './api'
import fxxk from "./fxxk.js";
import feishu from "./feishu.js";
import {CNMEn, sendLog} from "./tools";

async function asyncForEach(array, callback) {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array);
  }
}

const fk = new fxxk();
const fs = new feishu();
export default {
  components: {
    countTo,
    TourAdmin,
    ClientAdmin,
    ContactCard,
    ToolItemCard,
    FeeManager,
    TestFunctionView,
    VerifyShopListView
  },
  directives: {
    draggable
  },
  data: function () {
    return {
      banned: true, //工具箱禁用
      logo,
      toolXundian,
      toolMore,
      toolClient,
      toolWallet,
      toolShenpi,
      fk,
      fs,
      isInvalid: false,
      showTourAdminDrawer: false,
      showClientAdminDrawer: false,
      showFeeManagerDrawer: false,
      showTestDrawer: false,
      showTestDrawer_dev: false,
      updateDialogVisible: false,
      selectedText: "",
      searchContent: "",
      config_checked_chenlie: false,
      observer: null,
      fullscreenLoading: false,
      config_checked_chenlie_ceng: true,
      config_checked_chenlie_paimian: true,
      config_checked_watermark: true,
      config_menu_show: true,
      page: 1,
      moveDataelse: {
        x: null,
        y: null
      },
      year: 2022,
      month: 4,
      dialogVisible_shenpi: false,
      totalShenpiNum: 0,
      tmp_totalShenpiNum: 0,
      disable: false,
      version: "1.3.5",
      countTimes: 0 // 累计使用次数
    }
  },
  methods: {
    async handleShenpi(){ //批量审批
      const _this = this;
      let  ret = await api_getShenpiList(_this.year, _this.month);
      _this.totalShenpiNum = ret["total"]
      let times = 1;
      while(ret["dataList"].length>=1){
        _this.disable = true;
        console.log(times)
        const tmp = api_chenlieShenpi(ret["dataList"][0]["_id"], ret["dataList"][0]["application_form_id__c"],_this.year, _this.month)
        ret = await api_getShenpiList(_this.year, _this.month);
        _this.tmp_totalShenpiNum = ret["total"];
        times+=1;
      }
      _this.$message({
        showClose: true,
        message: '批量陈列审批成功！',
        type: 'success'
      });
      _this.disable = false;
    },
    async calcShenpi(){ //审批

    },
    refreshShopList() {
      this.$refs["verify-shop-list-view"].changeSelectType("");
    },
    confirmUpdatesDialog() {
      this.updateDialogVisible = false;
      document.querySelector("html").style="filter: grayscale(0%);"
      window.localStorage.setItem("version", this.version)
    },
    handleClose() {
      this.config_menu_show = !this.config_menu_show;
      window.localStorage.setItem("menu-show", this.config_menu_show);
    },
    async getFkSearchData(feeCode) {
      axios.post(
          `https://www.fxiaoke.com/FHH/EM1HNCRM/API/v1/object/search/service/search_data`,
          {"keyword": feeCode}
      )
          .then((res) => {
            console.log("fuckkkkkkkkk------->", res)
          })
    },
    handleSearch() {
      // 选择需要观察变动的节点
      const targetNode = document.querySelector(".xxvui-fl-feed-list");
      const config = {attributes: true, childList: true, subtree: true};
      const callback = function (mutationsList, observer) {
        // Use traditional 'for loops' for IE 11
        for (let mutation of mutationsList) {
          if (mutation.type === 'childList') {
            if (mutation.target == "ul.user-list") {
              console.log("aaa-------------->>>>>>>>>>>")
            } else {
              let tmpClass = mutation.target.getAttribute("class");
              if (tmpClass == "xxvui-fl-feed-list") {
                let a = document.querySelectorAll(".fl_cmpt_approval_flow_biz_info");
                let b = document.querySelectorAll(".xxvui-fl-header");
                let c = document.querySelectorAll(".wf-feed-box");
                let d = document.querySelectorAll(".faci-field-display_label");
                let e = document.querySelectorAll(".faci-field-display_value");
                let d_d = document.querySelectorAll(".fc_group--3 > .faci-field-display_label");
                let e_e = document.querySelectorAll(".faci-field-display_obj-ref");
                if (a.length > 0) {
                  a.forEach((item, index) => {
                    a[index].style.display = "none";
                    b[index].style.display = "none";
                    c[index].style.display = "none";
                  })
                  d.forEach((item) => {
                    item.style.display = "none";
                  })
                  e.forEach((item) => {
                    item.style.display = "none";
                  })
                  e_e.forEach((item) => {
                    item.style.display = "flex";
                  })
                  d_d.forEach((item) => {
                    item.style.display = "flex";
                  })
                }
              } else {
                console.log("---------》", tmpClass)
              }
            }
          } else if (mutation.type === 'attributes') {
          }
        }
      };
      const observer = new MutationObserver(callback);
      observer.observe(targetNode, config);
      if (this.searchContent != "") {
        this.getFkSearchData(this.searchContent);
      }
    },
    fetchCurrentPageChenlieType() {
      const _this = this;
      let text = "td-activity_agreement_id__c"
      let tbs = window.document.querySelectorAll(".td-activity_agreement_id__c");
      asyncForEach(tbs, async (tb) => {
        let id = tb.childNodes[1].childNodes[1].getAttribute("data-id");
        _this.fullscreenLoading = true;
        api_getFkChenlieType(id, _this.config_checked_chenlie_ceng, _this.config_checked_chenlie_paimian).then(res => {
          console.log('over----------------->', res);
          tb.childNodes[1].childNodes[1].innerText = res;
        });
        _this.fullscreenLoading = false;
      });
    },
    handleClickChecked_watermark(value) {
      const _this = this;
      _this.config_checked_watermark = value;
      window.localStorage.setItem("menu-showWatermark", value);
      let tbs = window.document.querySelector(".water-mark-bg");
      if (value) {
        tbs.style.display = "none";
      } else {
        tbs.style.display = "";
      }
    },
    handleClickChecked_chenlie(value) {
      const _this = this;
      if (value == "") {
        _this.config_checked_chenlie = !_this.config_checked_chenlie;
      } else if (value === "ceng") {
        _this.config_checked_chenlie_ceng = !_this.config_checked_chenlie_ceng;
        if (_this.config_checked_chenlie_ceng == false) {
          console.log("关闭自动更新陈列形式_显示层数");
          window.localStorage.setItem("menu-autoUpdateChenlie_ceng", false);
        } else {
          console.log("打开自动更新陈列形式_显示层数");
          window.localStorage.setItem("menu-autoUpdateChenlie_ceng", true);
        }
      } else if (value === "paimian") {
        _this.config_checked_chenlie_paimian = !_this.config_checked_chenlie_paimian;
        if (_this.config_checked_chenlie_paimian == false) {
          console.log("关闭自动更新陈列形式_显示排面");
          window.localStorage.setItem("menu-autoUpdateChenlie_paimian", false);
        } else {
          console.log("打开自动更新陈列形式_显示排面");
          window.localStorage.setItem("menu-autoUpdateChenlie_paimian", true);
        }
      }
      if (_this.config_checked_chenlie == false) {
        console.log("关闭自动更新陈列形式");
        window.localStorage.setItem("menu-autoUpdateChenlie", false);
      } else {
        console.log("打开自动更新陈列形式");
        window.localStorage.setItem("menu-autoUpdateChenlie", true);
        _this.fetchCurrentPageChenlieType();
      }
    },
    testFunction() {
      //this.fs.getSheetInfo("shtcnR78p1VkTysagGWtmOU9BKc")
      //this.fs.setSheetValuesByRange("shtcnR78p1VkTysagGWtmOU9BKc", "lLWRLI", "A1:A1", ["彭彭"])
      //this.fs.setSheetValuesListByRange("shtcnR78p1VkTysagGWtmOU9BKc", "lLWRLI", "A:Z", [["彭彭",11],["钉钉"]])
      //this.fs.getSheetValuesByRange("shtcnR78p1VkTysagGWtmOU9BKc", "lLWRLI", "A1:A1")
      //this.fs.setSheetCellsMerge("shtcnR78p1VkTysagGWtmOU9BKc", "lLWRLI", "A1:A2")
      //this.fs.insertImage("shtcnR78p1VkTysagGWtmOU9BKc", "lLWRLI", "A1:A1","https://www.fxiaoke.com/FSC/EM/File/GetByPath?path=N_202203_12_94a59a0e34a147ba9463a7273c65a705","测试图片")
      //this.fs.setSheetStyleByRange("shtcnR78p1VkTysagGWtmOU9BKc", "lLWRLI", "A:B", {"font": {"bold": true, "italic": true}})
      let sheetInfo = this.fs.generateFeishuLink("https://k11pnjpvz1.feishu.cn/sheets/shtcndW80FGw4ij34V0E3b3G42d?sheet=kEeZF7")
      console.log(sheetInfo)
    },
    getUserInfo() {
      let name = document.querySelector(".avatar-panel> a > .name");
      let post = document.querySelector(".avatar-panel> a > .post");
      try {
        name = name.innerHTML;
        post = post.innerHTML;
      } catch (e) {
        name = "";
        post = "";
      }
      return {
        name: name,
        post: post
      }
    }
  },
  created() {
    const _this = this;
    _this.config_checked_chenlie = JSON.parse(window.localStorage.getItem("menu-autoUpdateChenlie"));
    _this.config_checked_chenlie_ceng = JSON.parse(window.localStorage.getItem("menu-autoUpdateChenlie_ceng"));
    _this.config_checked_chenlie_paimian = JSON.parse(window.localStorage.getItem("menu-autoUpdateChenlie_paimian"));
    _this.config_checked_watermark = JSON.parse(window.localStorage.getItem("menu-showWatermark"))
    _this.config_menu_show = JSON.parse(window.localStorage.getItem("menu-show"))
    console.log(_this.config_checked_chenlie, _this.config_checked_chenlie_ceng, _this.config_checked_chenlie_paimian)
    //自动更新陈列形式
    const targetNode = document.querySelector("body");
    const config = {attributes: true, childList: true, subtree: true};
    const callback = function (mutationsList, observer) {
      mutationsList.forEach(({addedNodes}) => {
        addedNodes.forEach(tb => {
          if (tb.className == "td-activity_agreement_id__c" && _this.config_checked_chenlie) {
            let id = tb.childNodes[1].childNodes[1].getAttribute("data-id");
            api_getFkChenlieType(id, _this.config_checked_chenlie_ceng, _this.config_checked_chenlie_paimian).then(res => {
              console.log('api_getFkChenlieType----------------->', res);
              tb.childNodes[1].childNodes[1].innerText = res;
            });
          }
          if (tb.className == "water-mark-bg" && _this.config_checked_watermark) {
            tb.style.display = "none";
          }
        });
      });
    };
    this.observer = new MutationObserver(callback);
    this.observer.observe(targetNode, config);
    let data = {
      userInfo: this.getUserInfo()
    }
    let sendData = CNMEn(JSON.stringify(data));
    sendLog(sendData).then(res => {
      console.log("获取是用次数----->", res)
      _this.countTimes = res;
    })
    //弹窗更新
    let version = window.localStorage.getItem("version");
    if (version != _this.version) {
      this.updateDialogVisible = true;
    }
  }
}
</script>
<style scoped lang="less">
::v-deep .el-divider__text {
  font-weight: 600;
}

.Wokoo {
  background-color: #FEFFFE;
  box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  padding: 10px;
  cursor: pointer !important;
}

.menu {
  position: relative;
}

.Wokoo-header {
  font-size: 20px;
}

.title {
  cursor: pointer;
  width: 100%;
  text-align: center;
  font-size: 22px;
  font-weight: 600;

  span {
    font-weight: 400;
    margin-left: 4px;
    font-size: 12px;
  }

  margin-top: 30px;
  margin-bottom: 20px;
}


.countTo {
  margin-top: 25vh;
  font-size: 20px;
  text-align: center;
}

.dialog-content {
  margin: 0 auto;

  p {
    line-height: 32px;
    text-align: center;
  }

  .author {
    display: block;
    margin-right: 40px;
    margin-top: 10px;
    margin-left: auto;
    text-align: right;
  }

  .tips {
    margin-top: 10px;
    font-size: 12px;
    color: #8f959e;
    display: flex;
    flex-direction: column;

    a {
      text-align: center;
    }
  }
}
</style>
